//
//  PhotoRecord.m
//  XPhoto
//
//  Created by baboy on 2019/6/19.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "Post.h"
#import "QiniuConf.h"
#import "BKOperationQueue.h"
#import "BKOperation.h"
#import "User.h"
#import "NSDate+x.h"
#import "HttpResponse.h"
#import "Group.h"
#import "NSDate+x.h"
#import "Except.h"


@implementation Post


+ (id)searchWithArgs:(PostSearchArgs *)args
            callback:(void(^)(id task, id response, NSError *error))callback{
    id task = [BKApi request:API_POST_SEARCH
      parameters:args
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            id arr = nil;
            if (!error) {
                HttpResponse *response = [HttpResponse responseWithDictionary:json dataItemClass:[Post class]];
                if ([response isSuccess]) {
                    arr = response.data;
                }
                if(![response isSuccess]){
                    error = [NSError errorWithDomain:HttpRequestDomain code:response.status userInfo:@{NSLocalizedDescriptionKey:response.msg}];
                }
            }
            if (callback) {
                callback(task,arr, error);
            }
        }];
    return task;
}

+ (id)searchByTagWithArgs:(PostSearchArgs *)args
                 callback:(void(^)(id task, id response, NSError *error))callback{
    id task = [BKApi request:API_POST_SEARCH_BY_TAG
      parameters:args
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            id arr = nil;
            if (!error) {
                HttpResponse *response = [HttpResponse responseWithDictionary:json dataItemClass:[Post class]];
                if ([response isSuccess]) {
                    arr = response.data;
                }
                if(![response isSuccess]){
                    error = [NSError errorWithDomain:HttpRequestDomain code:response.status userInfo:@{NSLocalizedDescriptionKey:response.msg}];
                }
            }
            if (callback) {
                callback(task,arr, error);
            }
        }];
    return task;
}

+ (id)searchByTopicWithArgs:(PostSearchArgs *)args
                 callback:(void(^)(id task, id response, NSError *error))callback{
    id task = [BKApi request:API_POST_SEARCH_BY_TOPIC
      parameters:args
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            id arr = nil;
            if (!error) {
                HttpResponse *response = [HttpResponse responseWithDictionary:json dataItemClass:[Post class]];
                if ([response isSuccess]) {
                    arr = response.data;
                }
                if(![response isSuccess]){
                    error = [NSError errorWithDomain:HttpRequestDomain code:response.status userInfo:@{NSLocalizedDescriptionKey:response.msg}];
                }
            }
            if (callback) {
                callback(task,arr, error);
            }
        }];
    return task;
}

+ (id)searchBySerialWithArgs:(PostSearchArgs *)args
                    callback:(void(^)(id task, id response, NSError *error))callback{
    id task = [BKApi request:API_POST_SEARCH_BY_SERIAL
      parameters:args
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            id arr = nil;
            if (!error) {
                HttpResponse *response = [HttpResponse responseWithDictionary:json dataItemClass:[Post class]];
                if ([response isSuccess]) {
                    arr = response.data;
                }
                if(![response isSuccess]){
                    error = [NSError errorWithDomain:HttpRequestDomain code:response.status userInfo:@{NSLocalizedDescriptionKey:response.msg}];
                }
            }
            if (callback) {
                callback(task,arr, error);
            }
        }];
    return task;
}

+ (id)searchBySerialTagWithArgs:(PostSearchArgs *)args
                       callback:(void(^)(id task, id response, NSError *error))callback{
    id task = [BKApi request:API_POST_SEARCH_BY_SERIAL_TAG
      parameters:args
        callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
            id arr = nil;
            if (!error) {
                HttpResponse *response = [HttpResponse responseWithDictionary:json dataItemClass:[Post class]];
                if ([response isSuccess]) {
                    arr = response.data;
                }
                if(![response isSuccess]){
                    error = [NSError errorWithDomain:HttpRequestDomain code:response.status userInfo:@{NSLocalizedDescriptionKey:response.msg}];
                }
            }
            if (callback) {
                callback(task,arr, error);
            }
        }];
    return task;
}
+ (id)create:(Post*)record
      photos:(NSArray*)photos
photoUploadProgress:(void(^)(NSString *key, float p)) progress
  completion:(void(^)(void))callback{
    if (photos) {
        NSMutableArray *items = [NSMutableArray array];
        BKOperationQueue *queue = [[BKOperationQueue alloc] init];
        queue.maxConcurrentOperationCount = 1;
        WEAK(weakQueue, queue);
        [queue setCompletion:^{
            STRONG(strongQueue, weakQueue);
            //post
            record.items = items;
            NSMutableDictionary *param = [[record dict] mutableCopy];
            if (record.createTime) {
                [param setValue: [record.createTime format:DATE_FORMAT_PATTERN_FULL] forKey:@"createTime"];
            }
            [BKApi request:API_POST_CREATE
              parameters: param
                callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
                    DLOG(@"record:%@", json);
                }];
            [strongQueue isSuspended];
        }];
        for (NSInteger i = 0; i < photos.count; i++) {
            PhotoAsset *photoAsset = [photos objectAtIndex:i];
            bool isPhoto = photoAsset.asset.mediaType == PHAssetMediaTypeImage ? YES : NO;
            PostItem *postItem = [[PostItem alloc] init];
            postItem.type = isPhoto ? @"photo":@"video";
            postItem.width = photoAsset.width;
            postItem.height = photoAsset.height;
            [items addObject:postItem];
            
            BKOperation *op = [[BKOperation alloc] init];
            op.asynchronous = YES;
            NSDate *t = record.createTime?:[NSDate date];
            NSString *fn =  photoAsset.originPath ? [photoAsset.originPath lastPathComponent] : PHOTO_RANDOM_FILE_NAME(isPhoto ? @"png":@"mp4");
            NSString *path = [NSString stringWithFormat:@"/timeline/%ld/%@/%@",  [(User*)[User currentUser] uid],[t format:@"yyyyMMdd"], fn];
            WEAK(weakOp,op);
//            DLOG(@"====file:%@|exists:%d",photoAsset.originPath,[[NSFileManager defaultManager] fileExistsAtPath:photoAsset.originPath]);
            
            [op addExecutionBlock:^{
                if (photoAsset.originPath) {
                    [QiniuConf uploadFile:photoAsset.originPath
                                 fileName:path
                                 progress:progress
                               completion:^(QNResponseInfo * _Nonnull info, NSString * _Nonnull key, NSDictionary * _Nonnull resp) {
                        if(info.ok){
                            postItem.url = [NSString stringWithFormat:@"%@%@", [[QiniuConf defaultConf] domain], path];
                            [weakOp updateFinishedStatus:YES];
                        }else{
                            DLOG(@"QNResponseInfo1:%@, resp1:%@",info, resp);
                            [BKIndicator showTips:info.error.localizedDescription duration:3.0f completion:nil];
                        }
                    }];
                }else{
                    [QiniuConf uploadPHAsset:photoAsset.asset
                                 fileName:path
                                 progress:progress
                               completion:^(QNResponseInfo * _Nonnull info, NSString * _Nonnull key, NSDictionary * _Nonnull resp) {
                        if(info.ok){
                            postItem.url = [NSString stringWithFormat:@"%@%@", [[QiniuConf defaultConf] domain], path];
                            [weakOp updateFinishedStatus:YES];
                        }else{
                            DLOG(@"QNResponseInfo2:%@, resp2:%@",info, resp);
                            [BKIndicator showTips:info.error.localizedDescription duration:3.0f completion:nil];
                            [Except uploadException:[info description] callback:nil];
                        }
                    }];
                }
                
            }];
            [queue addOperation:op];
            if (photoAsset.type == PhotoAssetTypeVideo && photoAsset.thumbPath) {
                BKOperation *thumbOp = [[BKOperation alloc] init];
                thumbOp.asynchronous = YES;
                NSDate *t2 = [record.createTime?:[NSDate date] dateByAddingTimeInterval:10];
                NSString *thumbPath = [NSString stringWithFormat:@"/timeline/%ld/%@/%@",  [(User*)[User currentUser] uid],[t2 format:@"yyyyMMdd"], [photoAsset.thumbPath lastPathComponent]];
                WEAK(weakThumbOp,thumbOp);
                [thumbOp addExecutionBlock:^{
                    
                    [QiniuConf uploadFile:photoAsset.thumbPath
                                 fileName:thumbPath
                                 progress:progress
                               completion:^(QNResponseInfo * _Nonnull info, NSString * _Nonnull key, NSDictionary * _Nonnull resp) {
                        if(info.ok){
                            postItem.thumb = [NSString stringWithFormat:@"%@%@", [[QiniuConf defaultConf] domain], thumbPath];
                            [weakThumbOp updateFinishedStatus:YES];
                        }else{
                            DLOG(@"QNResponseInfo3:%@, resp3:%@",info, resp);
                            [BKIndicator showTips:info.error.localizedDescription duration:3.0f completion:nil];
                            [Except uploadException:[info description] callback:nil];
                        }
                    }];
                }];
                [queue addOperation: thumbOp];
            }
            
        }
    }
    return nil;
}

+ (NSMutableArray *)locationSerialGroup:(NSMutableArray*)groupArray withPhotoRecords:(NSArray<Post*>*)photoRecords{
    if (!groupArray) {
        groupArray = [NSMutableArray array];
    }
    for (NSInteger i = 0; i < photoRecords.count; i++) {
        Post *post = photoRecords[i];
        NSString *day = [post.createTime format:@"yyyy-MM-dd"];
        Group *grp = nil;
        if (groupArray.count > 0) {
            Group *lastGrp = groupArray.lastObject;
            //1
            if (!lastGrp.data || lastGrp.data.count == 0) {
                lastGrp.data = [NSMutableArray array];
                [lastGrp.data addObject:post];
                continue;
            }
            //2 比较地点
            if ([day isEqualToString:lastGrp.key] && post.lat && post.lng) {
                for (Post *existRecord in lastGrp.data) {
                    if (!existRecord.lat || !existRecord.lng){
                        break;
                    }
                    if(existRecord.addr && [existRecord.addr isEqualToString:post.addr]){
                        grp = lastGrp;
                        break;
                    }
                    CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:[post.lat doubleValue] longitude:[post.lng doubleValue]];
                    CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[existRecord.lat doubleValue] longitude:[existRecord.lng doubleValue]];
                    CLLocationDistance distance = [loc2 distanceFromLocation:loc1];
                    if(distance <10){
                        grp = lastGrp;
                        break;
                    }
                }// end dor
            }// if
        }
        if(!grp){
            grp = [[Group alloc] init];
            grp.title = post.addr?:day;
            grp.subtitle = day;
            grp.key = day;
            [groupArray addObject:grp];
        }
        if(!grp.data || grp.data.count == 0){
            grp.data = [NSMutableArray array];
        }
        [grp.data addObject:post];
    }
    return groupArray;
}
+ (NSMutableArray *)dateSerialGroup:(NSMutableArray*)groupArray withPhotoRecords:(NSArray<Post*>*)photoRecords{
    if (!groupArray) {
        groupArray = [NSMutableArray array];
    }
    for (NSInteger i = 0; i < photoRecords.count; i++) {
        Post *post = photoRecords[i];
        NSString *day = [post.createTime format:@"yyyy-MM-dd"];
        Group *grp = nil;
        if (groupArray.count > 0) {
            Group *lastGrp = groupArray.lastObject;
            //1
            if (!lastGrp.data || lastGrp.data.count == 0) {
                lastGrp.data = [NSMutableArray array];
                [lastGrp.data addObject:post];
                continue;
            }
            //2 同一天划到一组
            if ([day isEqualToString:lastGrp.key]) {
                grp = lastGrp;
            }// if
        }
        if(!grp){
            grp = [[Group alloc] init];
            grp.key = day;
            grp.title = day;
            grp.subtitle = day;
            [groupArray addObject:grp];
        }
        if(!grp.data){
            grp.data = [NSMutableArray array];
        }
        [grp.data addObject:post];
    }
    return groupArray;
}
+ (NSMutableArray *)tagSerialGroup:(NSMutableArray*)groupArray withPhotoRecords:(NSArray<Post*>*)photoRecords{
    if (!groupArray) {
        groupArray = [NSMutableArray array];
    }
    for (NSInteger i = 0; i < photoRecords.count; i++) {
        Post *post = photoRecords[i];
        NSString *day = [post.createTime format:@"yyyy-MM-dd"];
        Group *grp = nil;
        if (groupArray.count > 0) {
            Group *lastGrp = groupArray.lastObject;
            //1
            if (!lastGrp.data || lastGrp.data.count == 0) {
                lastGrp.data = [NSMutableArray array];
                [lastGrp.data addObject:post];
                continue;
            }
            //2 同一天划到一组
            if ([day isEqualToString:lastGrp.key]) {
                grp = lastGrp;
            }// if
        }
        if(!grp){
            grp = [[Group alloc] init];
            grp.key = day;
            grp.title = post.addr?:day;
            grp.subtitle = day;
            [groupArray addObject:grp];
        }
        if(!grp.data){
            grp.data = [NSMutableArray array];
        }
        [grp.data addObject:post];
    }
    return groupArray;
}
@end


@implementation PostSearchArgs



@end

@implementation PostLoc

@end
@implementation PostTopic

@end
